import React, {Component, Fragment} from 'react';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import {connect} from 'dva';
import {
    Button,
    Menu,
    Dropdown,
    Icon,
    Row,
    Col,
    Steps,
    Card,
    Popover,
    Badge,
    Table,
    Tooltip,
    Divider,
    Radio,
    Select,
    Modal,
    Form,
    Input,
    List,
    notification,
    Popconfirm,
    message,
} from 'antd';
const FormItem = Form.Item;
const {Option} = Select;
import classNames from 'classnames';
import DescriptionList from 'components/DescriptionList';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './OrderDetail.less';
import G from '../../utils/g';
import {status, statusMap} from './orderStatus';

const {Step} = Steps;
const {Description} = DescriptionList;
const ButtonGroup = Button.Group;
const {TextArea} = Input;

const getWindowWidth = () => window.innerWidth || document.documentElement.clientWidth;

@connect(({refundDetail, loading}) => ({
    refundDetail,
    loading: loading.effects['refundDetail/fetch'],
}))
@Form.create()
export default class AdvancedProfile extends Component {
    state = {
        selectedRows: [],
        expressShow: false,
        addressShow: false,
        addressType: 1,
        expressList: [],
    };

    componentDidMount() {
        const {dispatch, location} = this.props;
        this.id = G.getUrlValue('id', location.search);
        if (typeof this.id == 'undefined') {
            notification.error({
                message: '页面错误',
                description: '维权ID不能为空',
            });
        } else {
            dispatch({
                type: 'refundDetail/fetch',
                payload: {
                    refundId: this.id
                }
            });
            //获取商家退货地址
            dispatch({
                type: 'refundDetail/fetchAddress'
            });
        }

        this.setStepDirection();
        window.addEventListener('resize', this.setStepDirection);
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.setStepDirection);
        this.setStepDirection.cancel();
    }

    onOperationTabChange = key => {
        this.setState({operationkey: key});
    };
    handleCancel = ()=> {
        this.setState({
            expressShow: false
        });
    };
    bindShowPop = ()=> {
        this.setState({
            expressShow: true
        });
    }

    @Bind()
    @Debounce(200)
    setStepDirection() {
        const {stepDirection} = this.state;
        const w = getWindowWidth();
        if (stepDirection !== 'vertical' && w <= 576) {
            this.setState({
                stepDirection: 'vertical',
            });
        } else if (stepDirection !== 'horizontal' && w > 576) {
            this.setState({
                stepDirection: 'horizontal',
            });
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
            }
        });
    };

    handleExPressShow = (expressContent)=> {
        this.setState({
            expressShow: true,
            expressList: Array.isArray(expressContent) ? expressContent : []
        });
    };

    handleExpressHide = ()=> {
        this.setState({
            expressShow: false
        });
    };

    handleAddressShow = ()=> {
        this.setState({
            addressShow: true
        });
    };

    handleAddressHide = ()=> {
        this.setState({
            addressShow: false
        });
    };

    handleRefund = (type)=> {
        const {refundDetail, dispatch} = this.props;
        switch (type) {
            case 0 : //确认退款
            case 2 ://确认收货并退款
                dispatch({
                    type: 'refundDetail/sureRefund',
                    payload: {
                        refundId: refundDetail.id
                    }
                });
                break;
            case 1 :  //确认退款并等待退货
                this.setState({
                    addressShow: true
                });
                break;
        }
    };

    bindRefused = (payload)=> {
        this.props.dispatch({
            type: 'refundDetail/refused',
            payload
        })
    };

    bindRefundSuccess = (payload)=> {
        let {max, refund_price} = payload;
        max = Number(max);
        refund_price = Number(refund_price);

        if (refund_price > max) {
            message.error('打款金额不能大于退款金额');
            return false;
        }

        delete payload.max;

        this.props.dispatch({
            type: 'refundDetail/refundSuccess',
            payload
        })
    }

    bindChangeType = (e)=> {
        this.props.form.setFieldsValue({'addressInfo': e.target.value});
        this.setState({
            addressType: e.target.value
        });
    };

    handleSubmitAddress = (e)=> {
        e.preventDefault();
        const {addressType} = this.state;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                let payload = {
                    refundId: this.id,
                    address_info: {}
                };
                if (addressType == 0) {
                    payload.address_info = values;
                } else {
                    payload.address_info = {
                        id: addressType
                    }
                }
                this.props.dispatch({
                    type: 'refundDetail/sureRefund',
                    payload
                }).then(()=> {
                    this.setState({
                        addressShow: false
                    });
                });
            }
        });
    }

    render() {
        const {stepDirection, selectedRows, expressShow, addressShow, addressType, expressList} = this.state;
        const {refundDetail, loading} = this.props;
        const {order, order_goods} = refundDetail;
        const {getFieldDecorator} = this.props.form;

        const columns = [
            {
                title: '商品图片',
                dataIndex: 'img',
                key: 'img',
                render: (val)=> {
                    return <img src={`${val}?imageView2/2/w/50`} width={50} />
                }
            },
            {
                title: '商品名称',
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: '规格值',
                render(text, record) {
                    let sku = '';
                    for (let key in record.sku) {
                        sku = record.sku[key];
                    }
                    return sku;
                },
            },
            {
                title: '单价',
                dataIndex: 'price',
                key: 'price',
            },
            {
                title: '数量',
                dataIndex: 'count',
                key: 'count',
            },
            {
                title: '金额',
                render: (text, record)=> {
                    return (record.price * record.count)
                }
            },
            {
                title: '操作',
                render: (a, record)=> {
                    return <div>
                        <a onClick={ ()=> {
                            this.handleExPressShow(record.expressContent)
                        } }>查看物流</a>
                    </div>
                }
            },
        ];

        const extra = (
            <Row>
                <Col xs={24} sm={12}>
                    <div className={styles.textSecondary}>状态</div>
                    <div className={styles.heading}>{ status[refundDetail.status] }</div>
                </Col>
                <Col xs={24} sm={12}>
                    <div className={styles.textSecondary}>订单金额</div>
                    <div className={styles.heading}>¥ { refundDetail.price }</div>
                </Col>
            </Row>
        );

        const description = (
            <DescriptionList className={styles.headerList} size="small" col="2">
                <Description term="退款金额">{ refundDetail.refund_price }元</Description>
                <Description term="维权原因">{ refundDetail.reason }</Description>
                <Description term="订单号">{ refundDetail.orderId }</Description>
                <Description term="物流信息">{ refundDetail.expressName } { refundDetail.expressNo } <a
                    onClick={ ()=>{this.handleExPressShow(refundDetail.expressContent)} }>查看</a></Description>
                <Description term="买家">
                    {order.province}{order.city}{order.area}{order.address} {order.addressee} {order.phone}
                </Description>
                <Description term="昵称">{ order.nickname }</Description>
                <Description term="运费">{ refundDetail.freight }元</Description>
                <Description term="合计优惠">{ refundDetail.discount }元</Description>
                <Description term="实际总收">{ refundDetail.price }元</Description>
            </DescriptionList>
        );

        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            },
            getCheckboxProps: record => ({
                disabled: record.name === 'Disabled User', // Column configuration not to be checked
                name: record.name,
            }),
        };

        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 4},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 20},
            },
        };

        // const stepList = [
        //   <Step title="买家付款" description={desc1} />,
        //   <Step title="商家发货" description={desc2} />,
        //   <Step title="买家申请退款" description={desc1} />,
        //   <Step title="卖家确认退款退货" description={desc1} />,
        //   <Step title="买家退货" description={desc1} />,
        //   <Step title="卖家收货并退款" description={desc1} />
        // ]

        let myStep = [];
        myStep = refundDetail.status_records.map(v=> {
            return <Step key={'step' + v.id} title={v.status_desc} description={
                <div className={classNames(styles.textSecondary, styles.stepDescription)}>
                    <p>{v.remark}</p>
                    <div>{v.createTime}</div>
                </div>
            }/>
        });

        return (
            <PageHeaderLayout
                title={`维权号：${refundDetail.id}`}
                logo={
                    <img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/nxkuOJlFJuAUhzlMTCEe.png"/>
                }
                action={
                    <Fragment>
                        <ButtonGroup>
                            {
                                (refundDetail.status == 200 || refundDetail.status == 201 || refundDetail.status == 204) ?
                                    <Popconfirm placement="bottomRight"
                                                title={<TextArea id="reason" rows={4} placeholder="请输入您拒绝的原因"/>}
                                                okText="确定" cancelText="取消" onConfirm={()=> {
                                        this.bindRefused({
                                            refundId: refundDetail.id,
                                            reason: document.getElementById(`reason`).value
                                        })
                                    }}>
                                        <Button>拒绝</Button>
                                    </Popconfirm> : null
                            }
                            {
                                refundDetail.status == 200 ? <Button onClick={()=> {
                                    this.handleRefund(0)
                                }}>确认退款</Button> : null
                            }
                            {
                                refundDetail.status == 201 ? <Button onClick={()=> {
                                    this.handleRefund(1)
                                }}>确认退款并等待退货</Button> : null
                            }
                            {
                                refundDetail.status == 204 ? <Button onClick={()=> {
                                    this.handleRefund(2)
                                }}>确认收货并退款</Button> : null
                            }
                            {
                                ( refundDetail.status == 203 || refundDetail.status == 207) ?
                                    <Popconfirm placement="bottomRight"
                                                title={<Input id="refund_price" placeholder="请输入最终打款金额"/>} okText="确定"
                                                cancelText="取消" onConfirm={()=> {
                                        this.bindRefundSuccess({
                                            max: refundDetail.price,
                                            refundId: refundDetail.id,
                                            refund_price: document.getElementById(`refund_price`).value
                                        })
                                    }}><Button>财务确认打款</Button></Popconfirm> : null
                            }
                        </ButtonGroup>
                    </Fragment>
                }
                content={description}
                extraContent={extra}
            >
                <Card title="订单流程" style={{marginBottom: 24, overflow: 'auto'}} bordered={false}>
                    <Steps direction={stepDirection} progressDot={(dot, {status}) => dot}
                           current={refundDetail.status_records.length - 1}>
                        {myStep}
                    </Steps>
                </Card>
                <Card title="订单商品" style={{marginBottom: 24}} bordered={false}>
                    <Table
                        pagination={false}
                        loading={loading}
                        dataSource={[order_goods]}
                        columns={columns}
                        rowKey="goodsId"
                    />
                </Card>
                <Modal
                    title="退货地址"
                    visible={ addressShow }
                    onOk={this.handleSubmitAddress}
                    onCancel={this.handleAddressHide}
                    width={900}
                >
                    <Form style={{marginTop: '24px'}}>
                        <FormItem
                            {...formItemLayout}
                            label="收货信息"
                        >

                            {getFieldDecorator('addressInfo', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择收货信息',
                                    },
                                ],
                            })(
                                <Radio.Group onChange={this.bindChangeType}>
                                    {
                                        refundDetail.addressList.map(v=> {
                                            return <Radio style={{display: 'block', 'whiteSpace': 'nowrap'}} key={v.id}
                                                          value={v.id}>{`${v.area}${v.address} ${v.addressee} ${v.phone}`}</Radio>
                                        })
                                    }
                                    <Radio value="0">其它</Radio>
                                </Radio.Group>
                            )}
                        </FormItem>
                        {
                            addressType == 0 ? <div>
                                <FormItem
                                    {...formItemLayout}
                                    label="收件人"
                                >
                                    {getFieldDecorator('addressee', {
                                        rules: [
                                            {required: true, message: '请输入收件人'}
                                        ],
                                    })(
                                        <Input placeholder="请输入收件人"/>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label="联系电话"
                                >
                                    {getFieldDecorator('phone', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入正确的联系电话',
                                                pattern: /^\d{11}$/
                                            }
                                        ],
                                    })(
                                        <Input placeholder="请输入联系电话"/>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label="省市区"
                                >
                                    {getFieldDecorator('area', {
                                        rules: [
                                            {required: true, message: '请输入省市区地址'}
                                        ],
                                    })(
                                        <Input placeholder="请输入省市区地址"/>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label="详细地址"
                                >
                                    {getFieldDecorator('address', {
                                        rules: [
                                            {required: true, message: '请输入详细地址'}
                                        ],
                                    })(
                                        <Input placeholder="请输入详细地址"/>
                                    )}
                                </FormItem>
                            </div>
                                : null
                        }
                    </Form>
                </Modal>

                <Modal
                    title="物流信息"
                    visible={ expressShow }
                    onOk={this.handleExpressHide}
                    onCancel={this.handleExpressHide}
                >

                    <List
                        itemLayout="horizontal"
                        dataSource={expressList}
                        renderItem={item => (<List.Item>{item.context}{item.time}</List.Item>)}
                    ></List>
                </Modal>
            </PageHeaderLayout>
        );
    }
}
